<?php

namespace core\entity;

/**
 * Câu lệnh where
 *
 * @author BapCai
 */
class Criteria {

    private $where = "";
    private $start = true;

    public function match($key = [], $val = null, $operator = 'AND', $__IN_BOOLEAN_MODE = false) {
        if (!$this->start) {
            $this->where .= (trim(strtoupper($operator)) == 'AND') ? ' AND ' : ' OR ';
        }
        if ($__IN_BOOLEAN_MODE) {
            $key .= ' IN BOOLEAN MODE';
        }
        if (is_array($key)) {
            $key = '`' . implode('`', $key) . '`';
        }
        $this->where .= 'MATCH(`' . $key . '`) AGAINST ("' . $this->validate($val) . '")';
        $this->start = false;
        return $this;
    }

    public function andKey($key) {
        if (!$this->start) {
            $this->where .= ' AND ';
        }
        $this->where .= '`' . $key . '`';
        $this->start = false;
        return $this;
    }

    public function orKey($key) {
        if (!$this->start) {
            $this->where .= ' OR ';
        }
        $this->where .= '`' . $key . '`';
        $this->start = false;
        return $this;
    }

    public function is($val = null) {
        $this->where .= ' = "' . $this->validate($val) . '"';
        return $this;
    }

    public function ne($val = null) {
        $this->where .= ' != "' . $this->validate($val) . '"';
        return $this;
    }

    public function gt($val = null) {
        $this->where .= ' > "' . $this->validate($val) . '"';
        return $this;
    }

    public function gte($val = null) {
        $this->where .= ' >= "' . $this->validate($val) . '"';
        return $this;
    }

    public function lt($val = null) {
        $this->where .= ' < "' . $this->validate($val) . '"';
        return $this;
    }

    public function lte($val = null) {
        $this->where .= ' <= "' . $this->validate($val) . '"';
        return $this;
    }

    public function regex($val = null) {
        $this->where .= ' LIKE "' . $this->validate($val) . '"';
        return $this;
    }

    public function in($val = array()) {
        if (!is_array($val)) {
            $val = [$val];
        }
        $this->where .= ' in ("' . implode('","', $val) . '")';
        return $this;
    }

    public function validate($val = null) {
        $val = addslashes($val);
        return $val;
    }

    public function __toString() {
        return $this->where;
    }

}
